//
//  ObservableType+Extension.swift
//  HinsLive
//
//  Created by haoxian on 2019/4/21.
//  Copyright © 2019 Hins. All rights reserved.
//

import Foundation
import RxSwift


extension ObservableType where E: EventConvertible {
    func subscribe(onNext: @escaping (E.ElementType) -> Void, onError: @escaping  (Error) -> Void) -> Disposable {
        let result = share()
        return Disposables.create(result.elements().subscribe(onNext: { value in
            onNext(value)
        }), result.errors().subscribe(onNext: { error in
            onError(error)
        }))
    }
    
    func preDo(onNext: ((E.ElementType) -> Void)? = nil,
               onError:  ((Error) -> Void)? = nil,
               onCompleted:  (() -> Void)? = nil) -> Observable<E> {
        return self.do(onNext: { e in
            switch e.event {
            case .next(let value):
                onNext?(value)
            case .error(let error):
                onError?(error)
            case .completed:
                onCompleted?()
            }
        })
    }
}
